# 导入相关依赖
import os
import sys
sys.path.append('../')
import csv
import numpy as np
np.set_printoptions(threshold=np.inf)
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.font_manager
from pyod.models.knn import KNN
from pyod.models.abod import ABOD
from pyod.models.cblof import CBLOF
from pyod.models.feature_bagging import FeatureBagging
from pyod.models.hbos import HBOS
from pyod.models.iforest import IForest
from pyod.models.lof import LOF
from sklearn.preprocessing import MinMaxScaler
# 实验选取的属性
attribute = [
'diff.score',
'fixed.acidity',
'volatile.acidity',
'citric.acid',
'residual.sugar',
'chlorides',
'free.sulfur.dioxide',
'total.sulfur.dioxide',
'density',
'pH',
'sulphates',
'alcohol'
]
# 数据集路径
root = './data/wine/benchmarks/'
# 词典模型
random_state = np.random.RandomState(20)
outliers_fraction = 0.05
classifiers = {
'Angle-based Outlier Detector (ABOD)': ABOD(contamination=outliers_fraction),
'Cluster-based Local Outlier Factor (CBLOF)': CBLOF(contamination=outliers_fraction, check_estimator=False, random_state=random_state),
'Feature Bagging': FeatureBagging(LOF(n_neighbors=35), contamination=outliers_fraction, check_estimator=False, random_state=random_state),
'Histogram-base Outlier Detection (HBOS)': HBOS(contamination=outliers_fraction),
'Isolation Forest': IForest(contamination=outliers_fraction, random_state=random_state),
'K Nearest Neighbors (KNN)': KNN(contamination=outliers_fraction),
'Average KNN': KNN(method='mean', contamination=outliers_fraction)
}
# 导入数据集
files = os.listdir(root)
path = './data/wine/'
# 异常数据处理
for att in attribute[1:]:
save_file = path + att + '.txt'
fout = open(save_file, mode='w')
for file in files:
fout.write('\n\ndataset abalone: ' + file + '\n')
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = att
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
line = 'OUTLIERS: ' + str(n_outliers) + ' INLIERS: ' + str(n_inliers) + ' using ' + clf_name
fout.write(str(line) + '\n')
fout.close()
files = os.listdir(root)
# 采用与上述异常数据处理相似的方法
for file in files[:3]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[1]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
# OX1 - outlier feature 1, OX2 - outlier feature 2
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[2]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[3]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[4]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
Clustering Based Local Outlier Factor方法
它将数据分为小型集群和大型集群,然后根据点所属的簇的大小以及到最近的大簇的距离来计算异常分数
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[5]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[6]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
Clustering Based Local Outlier Factor方法
它将数据分为小型集群和大型集群,然后根据点所属的簇的大小以及到最近的大簇的距离来计算异常分数
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[7]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;
Clustering Based Local Outlier Factor方法
它将数据分为小型集群和大型集群,然后根据点所属的簇的大小以及到最近的大簇的距离来计算异常分数
files = os.listdir(root)
for file in files[:2]:
print('\n\ndataset wine:', file)
file = root + file
dataset = pd.read_csv(file)
former = attribute[0]
latter = attribute[8]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset[[former, latter]] = scaler.fit_transform(dataset[[former, latter]])
dataset[[former, latter]].head()
X1 = dataset[former].values.reshape(-1, 1)
X2 = dataset[latter].values.reshape(-1, 1)
X = np.concatenate((X1, X2), axis=1)
xx, yy = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
for i, (clf_name, clf) in enumerate(classifiers.items()):
clf.fit(X)
scores_pred = clf.decision_function(X) * -1
y_pred = clf.predict(X)
n_inliers = len(y_pred) - np.count_nonzero(y_pred)
n_outliers = np.count_nonzero(y_pred == 1)
plt.figure(figsize=(10, 10))
dfx = dataset
dfx['outlier'] = y_pred.tolist()
IX1 = np.array(dfx[former][dfx['outlier'] == 0]).reshape(-1, 1)
IX2 = np.array(dfx[latter][dfx['outlier'] == 0]).reshape(-1, 1)
OX1 = dfx[former][dfx['outlier'] == 1].values.reshape(-1, 1)
OX2 = dfx[latter][dfx['outlier'] == 1].values.reshape(-1, 1)
print('OUTLIERS : ', n_outliers, 'INLIERS : ', n_inliers, clf_name)
threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)
a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange')
b = plt.scatter(IX1, IX2, c='white', s=20, edgecolor='k')
c = plt.scatter(OX1, OX2, c='black', s=20, edgecolor='k')
plt.axis('tight')
plt.legend(
[a.collections[0], b, c],
['learned decision function', 'inliers', 'outliers'],
prop=matplotlib.font_manager.FontProperties(size=20),
loc=2)
plt.xlim((0, 1))
plt.ylim((0, 1))
plt.title(clf_name)
plt.show()
ABOD方法
它考虑每个点与其邻居之间的关系,它没有考虑这些邻居之间的关系,其加权余弦分数与所有邻居的方差可视为偏离分数;ABOD在多维数据上表现良好;
k-Nearest Neighbors Detector方法
对于任何数据点,到第k个最近邻居的距离可以被视为远离分数;PyOD支持三个kNN探测器: 最大:使用第k个邻居的距离作为离群值; 均值:使用所有k个邻居的平均值作为离群值得分; 中位数:使用与邻居的距离的中位数作为离群值得分;
Isolation Forest方法
它在内部使用scikit-learn库,在此方法中,使用一组树完成数据分区; 隔离森林提供了一个异常分数,用于查看结构中点的隔离程度, 然后使用异常分数来识别来自正常观察的异常值,隔离森林在多维数据上表现良好;
Histogram-based Outlier Detection方法
这是一种有效的无监督方法,它假设特征独立并通过构建直方图来计算异常值,它比多变量方法快得多,但代价是精度较低;
Local Correlation Integral (LOCI)方法
LOCI对于检测异常值和异常值组非常有效,它为每个点提供LOCI图,总结了该点周围区域内数据的大量信息,确定了簇,微簇,它们的直径以及它们的簇间距离;现有的异常检测方法都不能匹配此功能,因为它们只为每个点输出一个数字;
Feature Bagging方法
功能装袋检测器在数据集的各种子样本上安装了许多基本检测器,它使用平均或其他组合方法来提高预测精度,默认情况下,Local Outlier Factor(LOF)用作基本估算器。 但是,任何估计器都可以用作基本估计器,例如kNN和ABOD;特征装袋首先通过随机选择特征子集来构造n个子样本。 这带来了基本估计的多样性。 最后,通过平均或取所有基本检测器的最大值来生成预测分数;